# -*- coding: utf-8 -*-
import simplejson as json

from google.appengine.ext import webapp
from google.appengine.api import urlfetch

from django.template import  Node, TemplateSyntaxError, resolve_variable
from datetime import datetime

from appengine_utilities import sessions

import counter as m

register = webapp.template.create_template_register() 

class RangeNode(Node):
    def __init__(self, num, context_name):
        self.num, self.context_name = num, context_name
    def render(self, context):
        context[self.context_name] = range(int(self.num))
        return ""

class RangeNodeList(Node):
    def __init__(self, num, context_name):
        self.num, self.context_name = num, context_name
    def render(self, context):
        context[self.context_name] = range(resolve_variable(self.num, context))
        return ""

class GetValueList(Node):
    def __init__(self, list, index, context_name):
        self.list, self.index, self.context_name = list, index, context_name
    def render(self, context):
        context[self.context_name] = resolve_variable(self.list, context)[resolve_variable(self.index, context)]
        return ""

class Counter(Node):
    def __init__(self, ip, context_name):
        self.ip, self.context_name = ip, context_name
    
    def render(self, context):    
        ip = resolve_variable(self.ip, context)
        
        flg = True
        strResponse = ""

        regs = m.Register.gql("WHERE ip = :1 ORDER BY date DESC", ip).get()
        
        url = 'http://www.geoplugin.net/json.gp?ip=%s' % (ip)
        jsonContent = urlfetch.fetch(url).content
        jsonContent = jsonContent.replace('geoPlugin', '\"geoPlugin\" : ', 1)
        jsonContent = '{' + jsonContent + '}'
        jsonContent = jsonContent.replace('(', '')
        jsonContent = jsonContent.replace(')', '')
        result = json.loads(jsonContent)
        
        register = m.Register()
        register.ip = ip
        register.city = result['geoPlugin']['geoplugin_city']
        register.region = result['geoPlugin']['geoplugin_region']
        register.areaCode = result['geoPlugin']['geoplugin_areaCode']
        register.dmaCode = result['geoPlugin']['geoplugin_dmaCode']
        register.countryCode = result['geoPlugin']['geoplugin_countryCode']
        register.country = result['geoPlugin']['geoplugin_countryName']
        register.continentCode = result['geoPlugin']['geoplugin_continentCode']
        register.latitude = result['geoPlugin']['geoplugin_latitude']
        register.longitude = result['geoPlugin']['geoplugin_longitude']
        
        self.sess = sessions.Session(session_expire_time=3000)
        
        if not 'here' in self.sess:
            self.sess['here'] = 'here'
            register.put()
       
        counter = m.Register.all().count()
        
        tmp = str(counter)
        
        
        for i in tmp:
            strResponse += "<image src='/images/%s.gif'/>" % i
                    
        context[self.context_name] = strResponse + "<br>"
        return "" 

@register.tag
def num_range(parser, token):
    """
    Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates
    
    Syntax:
    {% num_range 5 as some_range %}
    
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}
    
    Produces:
    0: Something I want to repeat 
    1: Something I want to repeat 
    2: Something I want to repeat 
    3: Something I want to repeat 
    4: Something I want to repeat
    """
    try:
        fnctn, num, trash, context_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    if not trash == 'as':
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    return RangeNode(num, context_name)    

@register.tag
def num_range_list(parser, token):
    """
    Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates
    
    Syntax:
    {% num_range 5 as some_range %}
    
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}
    
    Produces:
    0: Something I want to repeat 
    1: Something I want to repeat 
    2: Something I want to repeat 
    3: Something I want to repeat 
    4: Something I want to repeat
    """
    try:
        fnctn, num, trash, context_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    if not trash == 'as':
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    return RangeNodeList(num, context_name)    

@register.tag
def get_value_list(parser, token):
    """
    Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates
    
    Syntax:
    {% num_range 5 as some_range %}
    
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}
    
    Produces:
    0: Something I want to repeat 
    1: Something I want to repeat 
    2: Something I want to repeat 
    3: Something I want to repeat 
    4: Something I want to repeat
    """
    try:
        fnctn, list, index, trash, context_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    if not trash == 'as':
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    return GetValueList(list, index, context_name)

@register.tag
def counter(parser, token):
    """
    Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates
    
    Syntax:
    {% num_range 5 as some_range %}
    
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}
    
    Produces:
    0: Something I want to repeat 
    1: Something I want to repeat 
    2: Something I want to repeat 
    3: Something I want to repeat 
    4: Something I want to repeat
    """
    try:
        fnctn, ip, trash, context_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    if not trash == 'as':
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    return Counter(ip, context_name)
